/**
 * Created by weid on 2016/9/21.
 */
import '../css/role_authorization.css';
import './dialog/css/relate.css';
import $ from 'jquery';
import angular from 'angular';
import util from '@yunke/core/util';
import ui from '@yunke/core/ui';
import 'angular-ui';

// tree-menu folding function
$(document).on('click.treeMenu', '.tree-menu [data-switch]', function (e) {
    e.stopPropagation();
    let $br = $(this).parents('.tree-branch');
    let $contentBox = $br.find('>ul');
    if (!$contentBox.is(':animated')) {
        $contentBox.stop().slideToggle();
        $br[$br.hasClass('tree-branch-expand') ? 'removeClass' : 'addClass']('tree-branch-expand');
    }
});

const app = angular.module('authorization', ['ngPublicUI']);

app.controller('ctrlAuthorization', ['$scope', 'sveRole', '$timeout', ($scope, sveRole, $timeout) => {

    // 新增角色
    $scope.addNewRoleTemplateUrl = require('./dialog/add_role.html');
    $scope.addNewRole = ($dialog, $dialogScope) => {
        $dialogScope.roleInfo = {
            roleType: 0,
            roleDesc: ''
        };
    };
    $scope.saveNewRole = ($dialog, $dialogScope) => {
        $scope.keyword = '';
        sveRole.addNewRole($dialogScope.roleInfo).success(() => {
            sveRole.renderRoleList($scope);
        });
    };

    // 渲染数据列表
    sveRole.renderRoleList($scope);
    $scope.searchRole = () => {
        sveRole.renderRoleList($scope);
    };

    // 角色切换事件
    $scope.changeItem = (item) => {
        $scope.curRoleId = item.role_id;
        sveRole.renderAuthList($scope);
    };

    // 编辑角色
    $scope.editRoleTemplateUrl = require('./dialog/edit_role.html');
    $scope.editRole = ($dialog, $dialogScope, item) => {
        $dialogScope.roleInfo = {
            roleName: item.role_name,
            roleDesc: item.remart_text
        };
    };
    $scope.saveEditRole = ($dialog, $dialogScope, item) => {
        item.role_name = $dialogScope.roleInfo.roleName;
        item.remart_text = $dialogScope.roleInfo.roleDesc;
        sveRole.saveEditRole(item);
    };

    // 删除角色
    $scope.delRole = (item, index, parentArray) => {
        sveRole.checkRoleRelate(item.role_id).success(res => {
            if (res.data.result == 1) {
                util.notify('当前角色已有关联的用户，不允许被删除');
            } else {
                util.confirm('确定删除角色吗？', {
                    ok() {
                        sveRole.delRole(item.role_id).success(() => {
                            parentArray.splice(index, 1);
                        });
                    }
                });
            }
        });
    };

    // 关联角色
    $scope.relateRoleTemplateUrl = require('./dialog/relate_role.html');
    $scope.relateRole = ($dialog, $dialogScope) => {
        $dialogScope.addActiveUser = (item) => {
            if (item.checked) {
                item.checked = false;
                let au = $dialogScope.activeUsers;
                let index = au.length;
                while (index--) {
                    if (item.UserGUID === au[index].UserGUID || item.UserGUID === au[index].user_id) {
                        break;
                    }
                }
                $dialogScope.activeUsers.splice(index, 1);
            } else {
                item.checked = true;
                $dialogScope.activeUsers.push(item);
            }
        };
        $dialogScope.removeActiveUser = (item, index) => {
            $dialogScope.userList.forEach(v => {
                if (v.UserGUID === item.UserGUID || v.UserGUID === item.user_id) {
                    v.checked = false;
                }
            });
            $dialogScope.activeUsers.splice(index, 1);
        };

        // 搜索
        $dialogScope.searchForOrgUser = () => {
            sveRole.renderUserList($dialogScope);
        };

        // 渲染组织用户与列表
        $timeout(() => {
            $dialogScope.curRoleId = $scope.curRoleId;
            sveRole.renderOrgList($dialogScope);
        }, 10);
    };
    $scope.saveRelateRole = ($dialog, $dialogScope) => {
        const params = {
            role_id: $dialogScope.curRoleId,
            userList: []
        };
        $dialogScope.activeUsers.forEach(userInfo => {
            params.userList.push(userInfo.UserGUID || userInfo.user_id);
        });
        sveRole.saveUserLsit(params).success(() => {
            ui.showTip('保存成功');
        });
    };

    // 全选权限
    $scope.selectAllAction = (item) => {
        item.checked = !item.checked;

        sveRole.actionForEach(item, (action) => {
            action.checked = item.checked;
        });
    };

    // 每一项权限点击事件
    $scope.selectCheckChange = () => {
        $scope.authList.forEach(item => {
            sveRole.actionForEach(item, (action) => {
                return action.checked;
            }, true);
        });
    };

    // 保存权限
    $scope.saveRoleAuth = () => {
        const params = {
            role_id: $scope.curRoleId,
            actions: []
        };
        $scope.authList.forEach(item => {
            sveRole.actionForEach(item, (action) => {
                if (action.checked) {
                    params.actions.push(action.action_id);
                }
            });
        });
        sveRole.saveRoleAuth(params).success(() => {
            ui.showTip('保存成功');
        });
    };
}]);

app.service('sveRole', ['$http', 'sveOrg', ($http, sveOrg)=> {
    return {
        addNewRole(params) {
            return $http.post(
                G_CONFIG['api_prefix'] + 'user-auth/save-role',
                {
                    role_id: null,
                    parent_id: params.roleType,
                    role_name: params.roleName,
                    comment: params.roleDesc
                }
            )
        },
        saveEditRole(params){
            return $http.post(
                G_CONFIG['api_prefix'] + 'user-auth/save-role',
                params
            )
        },
        delRole(role_id){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/delete-role',
                {
                    params: {
                        role_id
                    }
                }
            )
        },
        getRoleList(keyword){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/role-list',
                {
                    params: {
                        keyword
                    }
                }
            )
        },
        renderRoleList($scope){
            this.getRoleList($scope.keyword || '').success(res => {
                for (let i = 0, len = res.data.length; i < len; i++) {
                    if (res.data[i].children.length) {
                        $scope.curRoleId = res.data[i].children[0].role_id;
                        break;
                    }
                }
                $scope.listData = res.data;
                this.renderAuthList($scope);
            });
        },
        getAuthCheckedList(role_id = ''){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/get-role-auth-list',
                {
                    params: {
                        role_id
                    }
                }
            )
        },
        getAuthList(role_id = ''){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/get-all-auth-list',
                {
                    params: {
                        role_id
                    }
                }
            )
        },
        renderAuthList($scope){
            this.getAuthList($scope.curRoleId).success(res => {
                $scope.authList = res.data.authList;
                this.getAuthCheckedList($scope.curRoleId).success(checkRes => {
                    let arr = checkRes.data.authList;
                    $scope.authList.forEach(v => {
                        this.actionForEach(v, (action) => {
                            return action.checked = arr.indexOf(action.action_code) !== -1;
                        }, true);
                    });
                });
            });
        },
        actionForEach(item, exec, boot){
            let allChecked = true;
            if (item.actions instanceof Array) {
                item.actions.forEach(action => {
                    let reVal = exec(action);
                    if (boot && !reVal) {
                        allChecked = false;
                    }
                });
            }
            if (item.sub instanceof Array) {
                item.sub.forEach(sub => {
                    if (sub.actions instanceof Array) {
                        sub.actions.forEach(action => {
                            let reVal = exec(action);
                            if (boot && !reVal) {
                                allChecked = false;
                            }
                        });
                    }
                });
            }
            if (boot) {
                item.checked = allChecked;
            }
        },
        saveRoleAuth(params){
            return $http.post(
                G_CONFIG['api_prefix'] + 'user-auth/save-role-auth',
                params
            );
        },
        renderOrgList($dialogScope){
            sveOrg.getOrgList().success(res => {

                // 递归改变数据结构字段，设置 $scope.curOrgId
                function recursion(data) {
                    data.forEach(v => {
                        v.name = v.BUName;
                        v.id = v.BUGUID;
                        if (v.son instanceof Array && v.son.length) {
                            v.children = v.son;
                            recursion(v.son);
                        }
                        if (!$dialogScope.curOrgId && v.BUGUID) {
                            $dialogScope.curOrgId = v.BUGUID;
                        }
                    });
                }

                recursion(res.data.orgList);

                this.renderTreeMenu(res.data.orgList, $dialogScope);
                this.renderUserList($dialogScope);
            });
        },
        renderTreeMenu(data, $dialogScope){
            $('#org-tree').tree({
                autoOpen: 1,
                data: data
            }).on('tree.select', (event) => {
                $dialogScope.curOrgId = event.node.BUGUID;
                this.renderUserList($dialogScope);
            });
        },
        renderUserList($dialogScope){
            const params = {
                role_id: $dialogScope.curRoleId,
                buGUID: $dialogScope.curOrgId,
                keyword: $dialogScope.searchText
            };
            this.getUserList(params).success(res => {
                if (!$dialogScope.onceConcat) {
                    $dialogScope.onceConcat = true;
                    $dialogScope.activeUsers = res.data.userList.hasbingUserList || [];
                }
                $dialogScope.userList = res.data.userList.waitUserList;
                $dialogScope.userList.forEach(v => {
                    $dialogScope.activeUsers.forEach(activeUser => {
                        if (v.UserGUID === activeUser.UserGUID || v.UserGUID === activeUser.user_id) {
                            v.checked = true;
                        }
                    });
                });
            });
        },
        getUserList(params){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/wait-user-list',
                {
                    params
                }
            )
        },
        saveUserLsit(params){
            return $http.post(
                G_CONFIG['api_prefix'] + 'user-auth/save-role-user',
                params
            )
        },
        checkRoleRelate(role_id = ''){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/check-has-bind',
                {
                    params: {
                        role_id
                    }
                }
            )
        }
    };
}]);
